import 'package:mobile_app.core/core/domain/entities/learning_info/learning_info.dart';

abstract class CloseCurrentLearningInterval {
  LearningInfo call({
    required LearningInfo learningInfo,
    required DateTime currentLearningIntervalEndTime,
  });
}

class CloseCurrentLearningIntervalImpl implements CloseCurrentLearningInterval {
  const CloseCurrentLearningIntervalImpl();

  @override
  LearningInfo call({
    required LearningInfo learningInfo,
    required DateTime currentLearningIntervalEndTime,
  }) {
    final currentLearningIntervalStartTime = learningInfo.currentLearningIntervalStartTime;

    if (currentLearningIntervalStartTime == null) {
      return learningInfo;
    }

    final currentLearningInterval = LearningInterval(
      startTime: currentLearningIntervalStartTime,
      endTime: currentLearningIntervalEndTime,
    );

    final updatedLearningSessions = learningInfo.learningSessions.rebuild((learningSessions) {
      final lastSession = learningSessions.last;

      final updatedLastSessionLearningIntervals =
          lastSession.learningIntervals.rebuild((learningIntervals) {
        learningIntervals.add(currentLearningInterval);
      });

      learningSessions.last = lastSession.copyWith(
        learningIntervals: () => updatedLastSessionLearningIntervals,
      );
    });

    final updatedLearningInfo = learningInfo.copyWith(
      learningSessions: () => updatedLearningSessions,
      currentLearningIntervalStartTime: () => null,
      currentLearningIntervalLastKnownActivityTime: () => null,
    );

    return updatedLearningInfo;
  }
}
